package pseudoAssemblerCompiler.twopassassembler.view.windows;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TableColumn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pseudoAssemblerCompiler.twopassassembler.controller.OperationCodeController;
import pseudoAssemblerCompiler.twopassassembler.exceptions.RequiredDataNotSetException;
import pseudoAssemblerCompiler.twopassassembler.model.windows.ProgramFileContentProvider;
import pseudoAssemblerCompiler.twopassassembler.model.windows.ProgramFileLabelProvider;
import pseudoAssemblerCompiler.twopassassembler.view.util.DialogWindowContainer;
import pseudoAssemblerCompiler.twopassassembler.view.util.TableViewerContainer;

import java.io.File;
import java.net.URISyntaxException;

/**
 * User: Роман
 * Date: 22.03.12
 * Time: 18:18
 */
public class LoadProgramFileWindow implements Window {

    private static final Logger LOGGER =
            LoggerFactory.getLogger(LoadProgramFileWindow.class);

    private TableViewer _programFilesTable;
    private TableColumn _nameColumn;
    private TableColumn _sizeColumn;

    /**
     * Контроллер для вкладки редактора регламента опроса
     */
    private OperationCodeController _controller;

    private DialogWindowContainer _container;

    private Button _open;

    private Button _cancel;

    public LoadProgramFileWindow(Display aDisplay,
                                 String aNameOfWindow) {

        _container = new DialogWindowContainer(aDisplay, aNameOfWindow, 500, 300);

        TableViewerContainer container =
                new TableViewerContainer(_container.get_composite());
        _programFilesTable = container.get_tableViewer();
        _programFilesTable.getTable().setHeaderVisible(true);
        _programFilesTable.getTable().setLinesVisible(true);

        TableViewerColumn nameTVC1 = container.createColumn("Название");
        TableViewerColumn sizeTVC2 = container.createColumn("Размер");

        _nameColumn = nameTVC1.getColumn();
        _sizeColumn = sizeTVC2.getColumn();

        _programFilesTable.setContentProvider(new ProgramFileContentProvider());
        _programFilesTable.setLabelProvider(new ProgramFileLabelProvider());
        try {
            ClassLoader classLoader = LoadProgramFileWindow.class.getClassLoader();
//            InputStream is = classLoader.getResourceAsStream(fileName);
            LOGGER.debug("this.getClass().getResource(\"programms\").toURI() = {}",
                    classLoader.getResource("programms").toURI());
            String initdir = "programms";
            _programFilesTable.setInput(
                    new File(classLoader.getResource("programms").toURI()).listFiles());
        } catch (URISyntaxException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        _open = _container.createButton("Открыть");
        _cancel = _container.createButton("Отменить");

        container.listeners();
    }

    private void layouts() {
        FormData formData;

        formData = new FormData();
        formData.left = new FormAttachment(0, 0);
        formData.top = new FormAttachment(0, 0);
        formData.right = new FormAttachment(100, 0);
        formData.bottom = new FormAttachment(100, 0);
        _programFilesTable.getTable().setLayoutData(formData);

        formData = new FormData();
        formData.top = new FormAttachment(0, 10);
        formData.right = new FormAttachment(_cancel, -10);
        formData.height = 30;
        formData.width = 100;
        _open.setLayoutData(formData);

        formData = new FormData();
        formData.top = new FormAttachment(0, 10);
        formData.right = new FormAttachment(100, -20);
        formData.height = 30;
        formData.width = 100;
        _cancel.setLayoutData(formData);
    }

    protected void listeners() {
        _cancel.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                _container.dispose();
            }
        });

        _open.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                try {
                    openButtonTriggered();
                    _container.get_shell().dispose();
                } catch (RequiredDataNotSetException ex) {
                    _container.makeMessage(ex.getMessage());
                    if (null != ex.getControl()) {
                        setFocus(ex.getControl());
                    }
                }
            }
        });
    }

    protected void openButtonTriggered() throws RequiredDataNotSetException {
        File selectedFile =
                (File) ((IStructuredSelection) _programFilesTable.getSelection()).getFirstElement();
        if (null == selectedFile) {
            throw new RequiredDataNotSetException("Выберите программу для открытия или нажмите: Отмена.");
        }

        _controller.openProgram(selectedFile);
    }

    @Override
    public void create() {
        listeners();
        layouts();
        _container.open();
    }

    @Override
    public void setController(Object aController) {
        if (aController instanceof OperationCodeController) {
            _controller = (OperationCodeController) aController;
        }
    }

    public boolean setFocus(Control control) {
        return control.setFocus();
    }

}
